package com.cskaoyan._05servlet_configcontext;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

/**
 * @author Macro_Ray
 * @since 2024/5/3 下午7:48
 */
// ServletRequest 获取请求参数的不同方式

@WebServlet("/ss5")
public class ServletRequest2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取键值对形式的参数
        String username = request.getParameter("username");   // 根据参数名获取单个参数值
        System.out.println("username："+username);

        String[] hobbies = request.getParameterValues("hobby");  // 根据参数名获取多个参数值
        System.out.println("hobby："+Arrays.toString(hobbies));

        Enumeration<String> pnames = request.getParameterNames();    // 获取所有参数名
        while (pnames.hasMoreElements()) {   // 遍历所有参数名
            String s1 = pnames.nextElement();
            String[] s2 = request.getParameterValues(s1);
            if (s2.length>1){         // 若参数名对应多个值，则打印参数名和值
                System.out.println(s1 +"="+Arrays.toString(s2));
            }
            else{                     // 若参数名对应单个值，则打印参数名和值
                System.out.println(s1 +"="+s2[0]);
            }
        }

        // 返回所有的参数 map集合
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            String key = entry.getKey();
            String[] value = entry.getValue();
            if (value.length > 1){
                System.out.println(key+"="+Arrays.toString(value));
            }else {
                System.out.println(key+"="+value[0]);
            }

        }


        System.out.println("===============");







    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
